package com.webdev.base.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.webdev.base.pojo.Orders;
import com.webdev.base.pojo.User;
import com.webdev.base.service.IGoodsService;
import com.webdev.base.service.IOrderService;
import com.webdev.base.util.Constants;
import com.webdev.base.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private IOrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        log.info("message:" + message);
        SeckillMessage seckillMessage = JSONUtil.toBean(message, SeckillMessage.class);

        Integer goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodId(goodsId);
        if (goodsVo.getGoodsCount() <= 0) {
            redisTemplate.opsForValue().set(Constants.REDIS_EMPTYGOODSKEY + goodsVo.getGoodsId(), true);
            return;
        }

        //判断用户是否重复购买
        Orders order = (Orders) redisTemplate.opsForValue().get(Constants.REDIS_ORDERKEY + user.getUserId());
        if (order != null) {
            return;
        }

        orderService.secKill(user, goodsVo);
    }

}
